###
 # @Author: didiplus
 # @Description: 
 # @Date: 2025-06-19 23:13:00
 # @LastEditors: didiplus
 # @LastEditTime: 2025-06-19 23:23:21
 # @FilePath: /script/SecGuardian/modules/configure_sshd_config.sh
 # @Version: 1.0
### 
configure_sshd_config() {
    log_change() {
        echo "[修改] $1：$2 -> $3"
    }

    log_add() {
        echo "[新增] $1：设置为 $2"
    }

    log_ok() {
        echo "[跳过] $1：已符合要求"
    }

    # 1. 获取用户输入的端口
    while true; do
        read -p "请输入新的SSH端口 (1024-65535, 不能使用22): " custom_port
        if ! [[ "$custom_port" =~ ^[0-9]+$ ]]; then echo "错误：必须输入数字！"; continue; fi
        if (( custom_port < 1024 || custom_port > 65535 || custom_port == 22 )); then
            echo "错误：端口必须在1024-65535范围内，且不能为22！"; continue
        fi
        if ss -tuln | grep -q ":${custom_port}\b"; then
            echo "错误：端口 ${custom_port} 已被占用！"; continue
        fi
        TARGET_PORT=$custom_port
        break
    done
    echo "✅ 使用安全端口：$TARGET_PORT"

    SSHD_CONFIG="/etc/ssh/sshd_config"
    config_file="$SSHD_CONFIG"
    BACKUP_FILE="/etc/ssh/sshd_config.$(date +%Y%m%d%H%M%S)"
    cp -p "$SSHD_CONFIG" "$BACKUP_FILE"
    echo "✅ 已备份原始配置：$BACKUP_FILE"

    # 2. 替换 SSH 端口
    existing_ports=$(grep -i '^Port' "$SSHD_CONFIG" | awk '{print $2}' | sort -u)
    modified=false
    if [[ -n "$existing_ports" ]]; then
        for port in $existing_ports; do
            if [[ "$port" != "$TARGET_PORT" ]]; then
                sed -i "s/^Port $port/Port $TARGET_PORT/" "$SSHD_CONFIG"
                log_change "SSH端口" "$port" "$TARGET_PORT"
                modified=true
            else
                log_ok "SSH端口配置"
            fi
        done
    else
        echo "Port $TARGET_PORT" >> "$SSHD_CONFIG"
        log_add "SSH端口配置" "$TARGET_PORT"
        modified=true
    fi

    # 3. Protocol 2 强制设置
    protocol_line=$(grep -n "^Protocol" "$SSHD_CONFIG")
    if [[ -n "$protocol_line" ]]; then
        current_value=$(echo "$protocol_line" | awk '{print $2}')
        line_number=$(cut -d: -f1 <<< "$protocol_line")
        if [[ "$current_value" != "2" ]]; then
            sed -i "${line_number}s/\b$current_value\b/2/" "$SSHD_CONFIG"
            log_change "Protocol版本" "$current_value" "2"
            modified=true
        else
            log_ok "Protocol版本"
        fi
    else
        echo "Protocol 2" >> "$SSHD_CONFIG"
        log_add "Protocol版本" "2"
        modified=true
    fi

    # 4. 禁用 DNS 反向解析
    usedns_line=$(grep -n "^UseDNS" "$SSHD_CONFIG")
    if [[ -n "$usedns_line" ]]; then
        dns_value=$(echo "$usedns_line" | awk '{print $2}')
        if [[ "$dns_value" != "no" ]]; then
            sed -i "s/^UseDNS.*/UseDNS no/" "$SSHD_CONFIG"
            log_change "UseDNS" "$dns_value" "no"
            modified=true
        else
            log_ok "UseDNS"
        fi
    else
        echo "UseDNS no" >> "$SSHD_CONFIG"
        log_add "UseDNS" "no"
        modified=true
    fi

    # 5. 设置超时断开间隔
    interval_line=$(grep -n "^ClientAliveInterval" "$SSHD_CONFIG")
    interval_value=$(grep "^ClientAliveInterval" "$SSHD_CONFIG" | awk '{print $2}')
    if [[ -n "$interval_line" ]]; then
        line_number=$(cut -d: -f1 <<< "$interval_line")
        if [[ "$interval_value" != "600" ]]; then
            sed -i "${line_number}s/^ClientAliveInterval.*/ClientAliveInterval 600/" "$SSHD_CONFIG"
            log_change "ClientAliveInterval" "$interval_value" "600"
            modified=true
        else
            log_ok "ClientAliveInterval"
        fi
    else
        echo "ClientAliveInterval 600" >> "$SSHD_CONFIG"
        log_add "ClientAliveInterval" "600"
        modified=true
    fi

    # 6. 设置超时尝试次数
    count_line=$(grep -n "^ClientAliveCountMax" "$SSHD_CONFIG")
    if [[ -n "$count_line" ]]; then
        count_number=$(cut -d: -f1 <<< "$count_line")
        count_value=$(echo "$count_line" | awk -F ':' '{print $2}' | xargs | awk '{print $2}')
        if [[ "$count_value" != "2" ]]; then
            sed -i "${count_number}s/^ClientAliveCountMax.*/ClientAliveCountMax 2/" "$SSHD_CONFIG"
            log_change "ClientAliveCountMax" "$count_value" "2"
            modified=true
        else
            log_ok "ClientAliveCountMax"
        fi
    else
        echo "ClientAliveCountMax 2" >> "$SSHD_CONFIG"
        log_add "ClientAliveCountMax" "2"
        modified=true
    fi

    # 7. 禁止 root 用户远程登录
    root_login_line=$(grep -n -i "^PermitRootLogin" "$SSHD_CONFIG" | tail -1)
    if [[ -n "$root_login_line" ]]; then
        line_num=$(cut -d: -f1 <<< "$root_login_line")
        current_val=$(cut -d: -f2- <<< "$root_login_line" | awk '{print $2}')
        if [[ "$current_val" =~ ^(yes|Yes|YES)$ ]]; then
            sed -i "${line_num}s/^.*PermitRootLogin.*/PermitRootLogin no/" "$SSHD_CONFIG"
            log_change "PermitRootLogin" "$current_val" "no"
            modified=true
        else
            log_ok "PermitRootLogin"
        fi
    else
        echo "PermitRootLogin no" >> "$SSHD_CONFIG"
        log_add "PermitRootLogin" "no"
        modified=true
    fi

    # 8. 最终重启 SSH 服务
    if $modified; then
        echo "✅ 检测到配置已更改，正在重启 SSH 服务..."
        systemctl restart sshd && echo "✅ SSH服务已重启完成"
    else
        echo "✅ 所有配置均已符合基线，无需修改"
    fi
}